import ajax from "@/utils/ajax";
import { tableSelection, deleteConfirm } from "@/utils/elementui.js";
import date from "@/utils/date";
import axios from "axios";
const airCategoryIds = [27, 30, 32, 127];
//0-开关面板 1-计量空调 2-空调 3-计量设备
const CategoryArray = [
  [1, 9, 11, 12, 13, 14, 15],//开关面面板
  [27],//计量空调
  [30, 32, 127],//空调
  [28, 29, 33, 34],//计量插座
  [128],//红外
  [31],//门锁
];
export default {
  data() {
    return {
      userid: "",
      //网点数据
      organId: null,
      organOptions: [],
      //区域数据
      areaData: [],
      ProbeChannelProps: {
        children: 'children',
        label: 'name',
        value: 'id',
        checkStrictly: true
      },
      //设备列表
      prodData: [],
      permission: {
        add: false,
        modify: false,
        delete: false,
        add_operation: false,
        delete_operation: false,
      },
      //场景数据
      Scene_data: [],
      triggerAttr_Options: [
        { id: 1, name: "电压" },
        // { id: 2, name: "电流" },
        // { id: 3, name: "功率因素" },
        { id: 9, name: "功率" },
        { id: 4, name: "开关" },
       
      ],
      triggerAttr_filtrationOptions: [
        { id: 5, name: "红外", have: [128] },
        { id: 6, name: "室温", have: [27, 30, 32, 127] },
        { id: 6, name: "温度", have: [28, 29, 33, 34] },
        //{ id: 7, name: "设定温度", have: [27, 30, 32, 127] },
        { id: 8, name: "开锁", have: [31] },
      ],
      triggerCondition_Options: [
        { id: 1, name: "大于" },
        { id: 2, name: "小于" },
        { id: 3, name: "等于" },
      ],
      defer_Options: [
        {
          name: "立即执行",
          S: 0,
        },
        {
          name: "延迟执行",
          S: 1,
        },
      ],
      week_Options: [
        { id: 7, name: "周日" },
        { id: 1, name: "周一" },
        { id: 2, name: "周二" },
        { id: 3, name: "周三" },
        { id: 4, name: "周四" },
        { id: 5, name: "周五" },
        { id: 6, name: "周六" },
      ],
      //空调模式
      air_modeOptions: [
        {
          name: "自动", M: 0,
        },
        {
          name: "制冷", M: 1,
        },
        {
          name: "除湿", M: 2,
        },
        {
          name: "送风", M: 3,
        },
        {
          name: "制暖", M: 4,
        },
      ],
      air_speedOptions: [
        {
          name: "自动", W: 0,
        },
        {
          name: "1档", W: 1,
        },
        {
          name: "2档", W: 2,
        },
        {
          name: "3档", W: 3,
        },
      ],
      air_directionOptions: [
        {
          name: "自动", D: 0,
        },
        {
          name: "手动", D: 1,
        },
      ],
      //添加场景
      dialogAddSceneVisible: false,
      steps: 1,
      AddScene: {
        sceneId: null,
        sceneName: '',
        areaId: null,
        triggergroupId: null,//触发设备组id
        triggerprodId: [],//触发设备id
        sceneActionList: [],//触发设备列表
        sceneindex: '',//触发设备index
        //暂未使用
        triggerprodaction: null, //红外走动
        triggerprodtime: null,//红外停留
        triggerprodnum: null,//次数or时间

        taskgroupId: null,//任务设备组id
        taskprodId: [],//任务设备id
        addtaskprodId: null,
        sceneActionDetailList: [],//任务设备列表id
      },
      //设备分组
      SceneGrouplist: [],
      //触发待选设备
      triggerprodData: [],
      //任务待选设备
      taskAllprodData: [],
      taskprodData: [],
      //任务选中过滤已选
      taskprodId: [],
      prodprops: {
        key: "id",
        label: "channelName",
      },
      renderFunc(h, option) {
        return <span title={option.channelName}>{option.channelName}</span>;
      },
      Scenerulesname: {
        sceneName: [
          { required: true, message: '请填写场景名称', trigger: 'blur' }
        ],
      },
      triggerprodScenerules: {
        triggerprodId: [
          { required: true, message: '请选择触发设备', trigger: 'change' }
        ],
        triggerprodaction: [
          { required: true, message: '请选择动作', trigger: 'change' }
        ],
        triggerprodtime: [
          { required: true, message: '请填写停留时间', trigger: 'blur' }
        ],
        triggerprodnum: [
          { required: true, message: '请填写走动次数', trigger: 'blur' }
        ],
      },

      triggeraction: [
        {
          id: 1,
          name: '打开'
        },
        {
          id: 2,
          name: '关闭'
        },
        {
          id: 3,
          name: '长时间无人逗留'
        },
        {
          id: 4,
          name: '有人走动'
        },
      ],
      //任务设备修改
      dialogAddTaskprodVisible: false,
      dialogTaskprodEditVisible: false,
      editTaskprodObj: true,
      editTaskproddata: {},
      editTaskprodolddata: {},
      editTaskprodEditindex: null,
      //编辑管理触发设备
      dialogEditTriggerVisible: false,
      //场景触发设备
      triggerProd: [],
      editSceneTrigger: false,
      triggercollapse: ['1', '2'],
      //场景目标设备
      //编辑管理触发设备
      dialogEditTargetVisible: false,
      //场景触发设备
      targetProdlist: [],
      addtargetProd: false,
      //修改标题
      editSceneNameindex: null,
      //单条件多条件展示
      singshow: true,
      mulshow: true,
      //场景联动记录
      dialogSceneLinkageRecordVisible: false,
      sceneLinkageRecorddata: [],
      sceneLinkageRecordtitle: '',
      dialogBrowseVerifyVisible: false,
      browseVerifyData: [],
      dialogBrowseActionVisible: false,
      browseActionData: []
    };
  },
  created() {
    this.userid = this.$store.getters.user.id;
    this.getOrganListData();
  },
  mounted() {
    this.$store.dispatch("actions/dynamicTitleAction", this.$route.meta.title);
  },
  computed: {
    gettriggerAttr_Options: function () {
      return function (type) {
        let filtrationOptions = this.triggerAttr_filtrationOptions.filter(item => item.have.includes(parseInt(type)));
        let Attr_Options = [...this.triggerAttr_Options, ...filtrationOptions]
        return Attr_Options
      }

    },
    getSinglrOrMultiplefactorlist: function () {
      return function (data, index) {
        return data != null && data.length > 0 ? data.filter(item => item.singleton == index) : []
      }

    },
    getMoldCodeindex: function () {
      return function (probeType) {
        return CategoryArray.findIndex(category => category.includes(parseInt(probeType)));
      }
    },
    gettriggerAttr: function () {
      return function (probeType) {
        let MoldCodeindex = CategoryArray.findIndex(category => category.includes(parseInt(probeType)));
        switch (MoldCodeindex) {
          case 0:
            return 4
          case 4:
            return 5
          case 5:
            return 8
          default:
            return null
        }
      }
    },
    gettriggerCondition: function () {
      return function (probeType) {
        let MoldCodeindex = CategoryArray.findIndex(category => category.includes(parseInt(probeType)));
        switch (MoldCodeindex) {
          case 0:
          case 4:
          case 5:
            return 3
          default:
            return null
        }
      }
    },
    gettriggerValue: function () {
      return function (probeType) {
        let MoldCodeindex = CategoryArray.findIndex(category => category.includes(parseInt(probeType)));
        switch (MoldCodeindex) {
          case 0:
            return 0
          case 4:
            return 48
          case 5:
            return 1
          default:
            return null
        }
      }
    },
    protriggertxt: function () {
      return function (row) {
        switch (parseInt(row.triggerAttr)) {
          case 4:
            return parseInt(row.triggerValue) ? '设备开启' : '设备关闭';
          case 5:
            return row.triggerValue == 48 ? '红外检测有人' : '红外检测无人';
          case 8:
            return '开锁';
          default:
            {
              let triggerAttrOptions = [...this.triggerAttr_Options, ...this.triggerAttr_filtrationOptions]
              const triggerAttr = triggerAttrOptions.find(obj => obj.id === parseInt(row.triggerAttr))?.name || '';
              const Condition = this.triggerCondition_Options.find(obj => obj.id === parseInt(row.triggerCondition))?.name || '';
              return `${triggerAttr}${Condition}${row.triggerValue}`;
            }
        }

      }
    },
    prostatustxt: function () {
      return function (row) {


        switch (row.eventCode) {
          case 1:
            return '开锁';
          case 48:
            return '红外检测有人'
          case 49:
            return '红外检测无人';
          case 8:
            return '开锁';
          default:
            {
              let text = ''
              if (airCategoryIds.includes(parseInt(row.sceneAction.probeType))) {
                text = `室温:${row.indoorTemperature}℃ 设定温度:${row.airTemperature}℃`
              }
              return `开关状态:${row.state ? '开启' : '关闭'} 电压:${row.voltage}V 功率因数:${row.powerFactor} 电流:${row.current}` + text
            }
        }

      }
    },
    studyTitle: function () {
      switch (this.steps) {
        case 1:
          return "填写场景名称";
        case 2:
          return "创建触发条件";
        case 3:
          return "选择任务设备";
        case 4:
          return "添加触发设备";
        case 5:
          return `修改${this.AddScene.sceneActionList[0].channelName}触发条件`;
        case 6:
          return "修改场景名称";
        default:
          return "新增场景联动";
      }
    },
    studyWidth: function () {
      switch (this.steps) {
        case 1:
        case 6:
          return "500px";
        case 2:
          return "800px";
        case 3:
          return "800px";
        case 4:
        case 5:
          return "550px";
        default:
          return "800px";
      }
    },
    //空调温度
    airTemperatureset() {
      return function (index, targetCategoryId) {
        if (airCategoryIds.includes(parseInt(targetCategoryId))) {
          return index + '℃ /'
        } else {
          return '--'
        }
      }
    },
    //空调风量
    airSpeed() {
      return function (index, targetCategoryId) {
        if (airCategoryIds.includes(parseInt(targetCategoryId))) {
          let speedbj = this.air_speedOptions.find((obj) => obj.W == index);
          return speedbj ? speedbj.name : null;
        } else {
          return '--'
        }
      }
    },
    //空调风量
    airDirection() {
      return function (index, targetCategoryId) {
        if (airCategoryIds.includes(parseInt(targetCategoryId))) {
          let directionObj = this.air_directionOptions.find((obj) => obj.D == index);
          return directionObj ? directionObj.name : null;
        } else {
          return '--'
        }
      }
    },
    //空调模式
    airMode() {
      return function (index, targetCategoryId) {
        if (airCategoryIds.includes(parseInt(targetCategoryId))) {
          let ModeObj = this.air_modeOptions.find((obj) => obj.M == index);
          return ModeObj ? ModeObj.name : null;
        } else {
          return '--'
        }
      }
    },
  },
  methods: {
    // 获取网点列表
    getOrganListData() {
      ajax.get({
        url: this.$API.getUserOrgan + this.userid,
        success: (response) => {
          const resp = response.data;
          if (resp.length > 0) {
            this.organOptions = resp;
            this.organId = resp[0].id
            this.getSceneListdata()
            this.getSceneGroupData()
          } else {
            this.organOptions = [];
          }
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    //切换网点
    organChangeEvent() {
      this.OrganIdindex = this.organOptions.findIndex(data => data.id == this.organId)
      this.getSceneListdata()
      this.getSceneGroupData()
    },
    //获取场景列表
    getSceneListdata() {
      let self = this
      ajax.post({
        url: this.$API.getsceneList + this.organId,
        showLoading: false,
        success: (response) => {
          if (response.data.length > 0) {
            self.Scene_data = response.data;
          } else {
            self.Scene_data = []
          }

        }
      })
    },
    // 获取控制组的数据
    getSceneGroupData() {
      ajax.post({
        url: this.$API.getsceneGroupList + this.organId,
        success: (response) => {
          const resp = response.data;
          this.SceneGrouplist = resp;
        },
      });
    },
    editSceneName(row, index) {
      this.AddScene.sceneName = row.sceneName
      this.editSceneNameindex = index
      this.steps = 6
      this.dialogAddSceneVisible = true
    },
    //启用停用场景
    editSceneEnabled(value, row, enabled) {
      let data = value !== '' ? row : this.Scene_data[this.editSceneNameindex]
      //console.log(value)
      if (value === '') {
        data.sceneName = this.AddScene.sceneName
      }
      ajax.post({
        url: this.$API.editScene + data.id,
        data: data,
        showLoading: false,
        success: (response) => {
          this.$message({
            message: `${enabled != 1 ? '修改' : row.enabled == 1 ? '开启' : '停用'}成功`,
            type: "success",
          });
          this.dialogAddSceneVisible = false
        }
      })
    },
    //下一步
    nextStep(formName) {
      switch (this.steps) {
        case 1:
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let data = {
                sceneName: this.AddScene.sceneName,
                organId: this.organId
              }
              ajax.post({
                url: this.$API.createScene,
                data: data,
                success: (response) => {
                  if (response.success) {
                    this.AddScene.sceneId = response.data.id
                    this.AddScene.triggergroupId = null
                    this.steps++
                  }
                },
                error: (res) => {
                  this.$message({
                    message: res.message,
                    type: "error",
                  });
                },
              });

            } else {
              return false;
            }
          });

          break;
        case 2:
          this.$refs[formName].validate((valid) => {
            if (valid) {
              let probechaninofbool = true;
              let self = this
             
              let channelId = this.AddScene.sceneActionList
              .filter(data=>!airCategoryIds.includes(parseInt(data.probeType)))
              .map(data => data.channelId );
              axios
                .post(this.$API.triggerDeviceVerification, channelId)
                .then(function (res) {
                  if (Object.keys(res.data.data).length > 0) {
                    Object.keys(res.data.data).forEach(item => {
                      const obj = self.AddScene.sceneActionList.find(data => data.channelId == item);
                      
                      if (obj) {
                        obj.isExistTrigger = true;
                        obj.existTriggerList = res.data.data[item];
                      }

                    })
                    console.log(self.AddScene.sceneActionList);
                    self.$message({
                      message: '设备在其他场景中作为目标设备，请移除设备',
                      type: "error",
                    });
                  }
                  else {
                    if (self.AddScene.sceneActionList.some(item => {
                      const { channelName, channelId, triggerValue, triggerCondition, triggerAttr } = item;
                      const isInvalid = triggerValue === "" || triggerValue == null || triggerCondition == null || triggerAttr == null;
                      if (isInvalid) {
                        self.$message({
                          message: `请填写${channelName}触发条件`,
                          type: "error",
                        });
                        self.AddScene.sceneindex = channelId + '';
                      }
                      return isInvalid;
                    })) {
                      probechaninofbool = false;
                    }
                    if (probechaninofbool) {
                      let AddScene = self.AddScene
                      let data = {
                        groupId: AddScene.triggergroupId,
                        sceneId: AddScene.sceneId,
                        trigger: 1,
                        sceneActionList: AddScene.sceneActionList
                      }
                      ajax.post({
                        url: self.$API.sceneBindGroup,
                        data: data,
                        success: (response) => {
                          if (response.success) {
                            self.steps++
                            self.AddScene.taskgroupId = null
                          }
                        },
                        error: (res) => {
                          self.$message({
                            message: res.message,
                            type: "error",
                          });
                        },
                      });
                    }
                  }


                });

            } else {
              return false;
            }
          });
          break;
        case 3:
          {
            if (this.AddScene.sceneActionDetailList.length > 0) {
              //this.dialogAddSceneVisible = false
              let AddScene = this.AddScene
              let sceneActionDetailList = AddScene.sceneActionDetailList.map(({ channelId, channelName, delay, groupId, open,
                probeId, probeName, defertime, probeGuid, probeType, airMode, airSpeed, airTemperatureset, airWindDirection, effectivetime, effectiveweek }) => ({
                  channelId,
                  channelName,
                  delay,
                  groupId,
                  open,
                  probeGuid,
                  probeId,
                  probeName,
                  probeType,
                  sceneId: this.AddScene.sceneId,
                  item: JSON.stringify({ defertime: defertime, airMode: airMode, airSpeed: airSpeed, airTemperatureset: airTemperatureset, airWindDirection: airWindDirection, effectivetime: effectivetime, effectiveweek: effectiveweek })
                }));
              let data = {
                groupId: AddScene.taskgroupId,
                sceneId: AddScene.sceneId,
                trigger: 0,
                sceneActionDetailList: sceneActionDetailList
              }
              ajax.post({
                url: this.$API.sceneBindGroup,
                data: data,
                success: (response) => {
                  if (response.success) {

                    this.dialogAddSceneVisible = false
                    this.$message({
                      message: "场景创建成功",
                      type: "success",
                    });
                  }
                },
                error: (res) => {
                  this.$message({
                    message: res.message,
                    type: "error",
                  });
                },
              });
            }
            else {
              this.$message({
                message: '请添加目标设备',
                type: "error",
              });
            }
            //console.log(data)
            break;
          }
        default:
          break;
      }
    },
    //条件设备存在触发设备 删除条件设备
    delisExistTrigger(channelId) {
      let triggerprodId = this.triggerprodData.find(data => data.channelId == channelId).id;
      let triggerindex = this.AddScene.triggerprodId.findIndex(value => value == triggerprodId);
      if (triggerindex > -1) {
        this.AddScene.triggerprodId.splice(triggerindex, 1);
      }
      let sceneActionListindex = this.AddScene.sceneActionList.findIndex((item) => item.channelId == channelId)
      this.AddScene.sceneActionList.splice(sceneActionListindex, 1)
    },
    //
    handlebindScene(id) {
      this.steps = 3
      this.AddScene.sceneId = id
      this.dialogAddSceneVisible = true
    },
    // 删除场景
    handleDeleteScene(id) {
      deleteConfirm(this).then((res) => {
        if (res) {
          ajax.post({
            url: this.$API.delScene + id,
            success: (response) => {
              if (response.success) {
                this.getSceneListdata();
                this.$message({
                  message: response.message,
                  type: "success",
                });
              }
            },
            error: (response) => {
              this.$message({
                message: response.message,
                type: "error",
              });
            },
          });
        }
      });
    },
    //设备组改变
    triggergroupchange(type) {
      //type=1触发组 type=2任务组
      this.getSceneGroupProddata(type)
    },
    // 获取触发分组下的设备
    getSceneGroupProddata(type) {
      let po_id = type == 1 ? this.AddScene.triggergroupId : this.AddScene.taskgroupId;
      let self = this
      ajax.post({
        url: this.$API.sceneGroupDetailList + po_id,
        // data: { id: po_id },
        success: (response) => {
          if (type == 1) {
            if (this.steps == 2) {
              this.triggerprodData = response.data;
              this.AddScene.triggerprodId = []
              this.AddScene.sceneActionList = []
            } else if (this.steps == 4) {
              let triggerProdData = [...response.data];
              let triggerProd = [...self.triggerProd];
              const diff = triggerProdData.filter(item1 => !triggerProd.some(item2 => item2.channelId == item1.channelId));
              this.triggerprodData = diff
            }
          }
          if (type == 2) {
            let responsedata = response.data.filter(item => item.probeType != 128 && item.probeType != 31);
            //已有目标设备 添加新设备
            if (this.addtargetProd) {
              let taskProdData = [...responsedata];
              let taskProd = [...self.targetProdlist];
              const diff = taskProdData.filter(item1 => !taskProd.some(item2 => item2.channelId == item1.channelId));
              this.taskprodData = diff
              this.editTaskproddata = {}
              this.editTaskprodolddata = {}
              this.editTaskprodObj = false
            }
            //创建目标设备
            else {
              this.taskprodData = responsedata
              this.taskAllprodData = responsedata;
            }

            this.AddScene.taskprodId = []
            this.AddScene.addtaskprodId = null
            this.AddScene.sceneActionDetailList = []
          }
        },
      });
    },
    //设备下拉收起改变
    triggerprodvisiblechange(callback) {
      //console.log(callback)
      if (!callback) {
        this.triggerprodchange()
      }
    },
    //设备减少改变
    triggerprodremovechange() {
      this.triggerprodchange()
    },
    //触发设备改变事件
    triggerprodchange(callback) {
      //console.log(callback)
      //console.log(this.AddScene.triggerprodId)
      if (!callback) {
        let matchingProducts = []
        if (this.steps == 2) {
          matchingProducts = this.triggerprodData.filter(
            product => this.AddScene.triggerprodId.includes(product.id)
          );
        } else if (this.steps == 4) {
          matchingProducts = this.triggerprodData.filter(
            product => product.id == this.AddScene.triggerprodId
          );
        }
        let data = matchingProducts.map(({ channelId, channelName, probeId, probeName, probeGuid, probeType }) => ({
          channelId,
          channelName,
          probeId,
          probeGuid,
          probeName,
          probeType,
          sceneId: this.AddScene.sceneId,
          groupId: this.AddScene.triggergroupId,
          singleton: 1,
          organId: this.organId,
          triggerAttr: this.gettriggerAttr(probeType),
          triggerCondition: this.gettriggerCondition(probeType),
          triggerValue: this.gettriggerValue(probeType),
          MoldCodeindex: this.getMoldCodeindex(probeType),
          isExistTrigger: false,
          existTriggerList: [],
        }));
        this.AddScene.sceneActionList = data
        this.AddScene.sceneindex = data.length > 0 ? data[0].channelId + '' : ''
        //console.log(this.AddScene.sceneActionList)
      }
    },
    //触发属性改变
    triggerAttrchange(row) {
      switch (row.triggerAttr) {
        case 4:
          row.triggerCondition = 3
          row.triggerValue = 0
          break;
        case 8:
          row.triggerCondition = 3
          row.triggerValue = 1
          break;
        case 6:
        case 7:
          row.triggerValue = 26
          row.triggerCondition = null
          break;
        default:
          row.triggerCondition = null
          row.triggerValue = null
          break;
      }

    },
    //关闭创建场景弹窗触发
    closeAddScene() {
      if (this.steps != 4 && this.steps != 5) {
        this.getSceneListdata()
        this.AddScene.triggergroupId = null
        this.AddScene.taskgroupId = null
      }
      this.$refs["addSceneForm"].resetFields();
      this.$refs["triggerprodScene"].resetFields();
      this.taskprodData = []
      this.taskAllprodData = []
      this.triggerprodData = []
      this.AddScene.triggerprodId = []

      this.AddScene.sceneActionList = []
      this.AddScene.sceneName = ''
      this.AddScene.sceneActionDetailList = []
      this.editSceneNameindex = null
      this.taskprodId = []
      this.steps = 1
      this.singshow = true
      this.mulshow = true

    },
    closeTaskprod() {
      this.$refs.prodtransfer.clearQuery('left')
      // 清空右边搜索
      this.$refs.prodtransfer.clearQuery('right')
    },
    //添加任务设备弹窗
    handleAddTaskprod() {
      //this.AddScene.taskgroupId = null
      let taskprodData = [...this.taskAllprodData];
      let taskprodId = [...this.AddScene.taskprodId];
      this.taskprodId = []
      const diff = taskprodData.filter(item1 => !taskprodId.some(item2 => item2 === item1.id));
      this.taskprodData = [...diff]
      this.dialogAddTaskprodVisible = true
    },
    //提交添加任务设备
    submitAddtaskprod() {
      this.dialogAddTaskprodVisible = false
      const matchingProducts = this.taskprodData.filter(
        product => this.taskprodId.includes(product.id)
      );

      let data = matchingProducts.map(({ channelId, channelName, probeId, probeName, probeGuid, probeType }) => ({
        channelId,
        channelName,
        probeId,
        probeGuid,
        probeName,
        probeType,
        sceneId: this.AddScene.sceneId,
        groupId: this.AddScene.taskgroupId,
        open: 0,
        delay: 0,
        item: '',
        defertime: 0,
        airMode: 1,
        airSpeed: 1,
        airTemperatureset: 28,
        airWindDirection: 1,
        isair: airCategoryIds.includes(parseInt(probeType)),
        effectivetime: ['00:00', '23:59'],
        effectiveweek: [1, 2, 3, 4, 5, 6, 7],
      }));
      this.AddScene.taskprodId.push(...this.taskprodId)
      this.AddScene.sceneActionDetailList.push(...data)
    },
    //编辑任务设备
    handleEdit(row, index, type) {
      if (type == 'edit') {
        this.editTaskprodObj = true
        this.addtargetProd = false

      }
      else {
        this.editTaskprodObj = false
        this.addtargetProd = true
        this.AddScene.taskgroupId = null
        this.AddScene.addtaskprodId = null
      }
      this.editTaskproddata = row
      this.editTaskprodolddata = { ...row }
      this.editTaskprodEditindex = index
      this.dialogTaskprodEditVisible = true

    },
    //编辑开启关闭
    //编辑任务设备
    handleopenEdit(row, index) {
      this.editTaskprodObj = true
      this.addtargetProd = false
      this.editTaskproddata = row
      this.editTaskprodolddata = { ...row }
      this.editTaskprodEditindex = index
      this.editSceneTarget()

    },
    //取消编辑
    closeTaskprodEdit() {

      //console.log(this.editTaskprodolddata)
      //编辑现有的
      if (!this.addtargetProd) {
        if (this.dialogEditTargetVisible) {
          this.$set(this.targetProdlist, this.editTaskprodEditindex, this.editTaskprodolddata);
        }
        //创建时修改
        else {
          this.$set(this.AddScene.sceneActionDetailList, this.editTaskprodEditindex, this.editTaskprodolddata);
        }
        this.AddScene.taskgroupId = null
      }
      else {
        this.AddScene.taskgroupId = null
        this.AddScene.addtaskprodId = null
      }
      this.dialogTaskprodEditVisible = false

    },
    //删除任务设备
    handleDelete(index) {
      this.AddScene.taskprodId.splice(index, 1)
      this.AddScene.sceneActionDetailList.splice(index, 1)
    },


    //管理触发设备
    handleSceneTrigger(id) {
      let self = this
      ajax.post({
        url: this.$API.sceneTrigger + id,
        // data: { id: po_id },
        success: (response) => {
          if (response.data != null && response.data.length > 0) {
            self.dialogEditTriggerVisible = true
            self.triggerProd = response.data[0].sceneActionList
            self.AddScene.sceneId = id
            self.AddScene.triggergroupId = response.data[0].id
          } else {
            self.steps = 2
            self.dialogAddSceneVisible = true
            self.AddScene.sceneId = id
            self.AddScene.triggergroupId = null
          }
        },
      });

    },
    //添加触发设备
    editAddTrigger(type, row) {
      if (type == 'add') {
        this.getSceneGroupProddata(1)
        this.steps = 4
      }
      else {
        row.triggerAttr = parseInt(row.triggerAttr)
        row.triggerCondition = parseInt(row.triggerCondition),
          row.triggerValue = parseInt(row.triggerValue),
          row.MoldCodeindex = this.getMoldCodeindex(row.probeType)
        this.AddScene.sceneindex = row.channelId + '';
        this.AddScene.sceneActionList = [{ ...row }]
        this.steps = 5
      }
      this.dialogAddSceneVisible = true
    },
    //提交编辑确定提交触发设备
    addoreditSceneTrigger(formName) {
      let sceneId = this.AddScene.sceneId
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let probechaninofbool = true;
          let self = this
          let channelId = this.AddScene.sceneActionList
          .filter(data=>!airCategoryIds.includes(parseInt(data.probeType)))
          .map(data => data.channelId );
          axios
            .post(this.$API.triggerDeviceVerification, channelId)
            .then(function (res) {
              if (Object.keys(res.data.data).length > 0 && self.steps == 4) {
                Object.keys(res.data.data).forEach(item => {
                  const obj = self.AddScene.sceneActionList.find(data => data.channelId == item);
                  if (obj) {
                    obj.isExistTrigger = true;
                    obj.existTriggerList = res.data.data[item];
                  }

                });
                self.$message({
                  message: '设备在其他场景中作为目标设备，请重新选择',
                  type: "error",
                });
              }
              else {
                if (self.AddScene.sceneActionList.some(item => {
                  const { channelName, channelId, triggerValue, triggerCondition, triggerAttr } = item;
                  const isInvalid = triggerValue === "" || triggerValue == null || triggerCondition == null || triggerAttr == null;
                  if (isInvalid) {
                    self.$message({
                      message: `请填写${channelName}触发条件`,
                      type: "error",
                    });
                    self.AddScene.sceneindex = channelId + '';
                  }
                  return isInvalid;
                })) {
                  probechaninofbool = false;
                }
                if (probechaninofbool) {
                  let url = self.steps == 4 ? self.$API.addSceneTrigger : self.$API.editSceneTrigger + self.AddScene.sceneActionList[0].id
                  let message = self.steps == 4 ? '添加成功' : '修改成功'
                  ajax.post({
                    url: url,
                    data: self.AddScene.sceneActionList[0],
                    success: (response) => {
                      if (response.success) {
                        self.$message({
                          message: message,
                          type: "success",
                        });
                        self.dialogAddSceneVisible = false
                        self.handleSceneTrigger(sceneId)
                      }
                    },
                    error: (res) => {
                      self.$message({
                        message: res.message,
                        type: "error",
                      });
                    },
                  });
                }
              }
            })

        }
      })
    },

    //删除触发设备
    delSceneTrigger(id) {
      let sceneId = this.AddScene.sceneId
      deleteConfirm(this).then((res) => {
        if (res) {
          ajax.post({
            url: this.$API.delSceneTrigger + id,
            success: (response) => {
              if (response.success) {
                this.handleSceneTrigger(sceneId);
                this.$message({
                  message: response.message,
                  type: "success",
                });
              }
            },
            error: (response) => {
              this.$message({
                message: response.message,
                type: "error",
              });
            },
          });
        }
      });
    },
    //管理目标设备
    handleSceneTarget(id) {
      let self = this
      ajax.post({
        url: this.$API.sceneTarget + id,
        // data: { id: po_id },
        success: (response) => {
          self.dialogEditTargetVisible = true
          self.AddScene.sceneId = id
          let data = response.data.map(({ item, ...rest }) => {
            const parsedItem = JSON.parse(item);
            return {
              ...rest,
              ...parsedItem,
              isair: airCategoryIds.includes(parseInt(rest.probeType))
            };
          });
          console.log(data)
          self.targetProdlist = data
        },
      });
    },

    //删除目标设备
    delSceneTarget(id) {
      let sceneId = this.AddScene.sceneId
      deleteConfirm(this).then((res) => {
        if (res) {
          ajax.post({
            url: this.$API.delSceneTarget + id,
            success: (response) => {
              if (response.success) {
                this.handleSceneTarget(sceneId);
                this.$message({
                  message: response.message,
                  type: "success",
                });
              }
            },
            error: (response) => {
              this.$message({
                message: response.message,
                type: "error",
              });
            },
          });
        }
      });
    },
    //提交修改目标设备
    editSceneTarget() {
      let sceneId = this.AddScene.sceneId
      let data = [{ ...this.editTaskproddata }].map(({ ...rest }) => {
        return {
          ...rest,
          item: JSON.stringify({ defertime: rest.defertime, airMode: rest.airMode, airSpeed: rest.airSpeed, airTemperatureset: rest.airTemperatureset, airWindDirection: rest.airWindDirection, effectivetime: rest.effectivetime, effectiveweek: rest.effectiveweek })
        };
      });
      let url = this.addtargetProd ? this.$API.addSceneTarget : this.$API.editSceneTarget + data[0].id
      let bool = false
      if (this.AddScene.addtaskprodId == null && this.addtargetProd) {
        this.$message({
          message: `请选择目标设备`,
          type: "error",
        });
      }
      else {
        bool = true
      }
      //console.log(data)
      if (bool) {
        const result = this.targetProdlist.reduce((acc, cur) => {
          const foundIndex = acc.findIndex(item => item == cur.groupId);
          if (foundIndex === -1) {
            acc.push(cur.groupId);
          }
          return acc;
        }, [])
        //console.log(result)
        //console.log(result.includes(data[0].groupId))
        if (result.includes(data[0].groupId)) {
          ajax.post({
            url: url,
            data: data[0],
            success: (response) => {
              if (response.success) {
                this.handleSceneTarget(sceneId);
                this.dialogTaskprodEditVisible = false
                this.addtargetProd = false
                this.$message({
                  message: response.message,
                  type: "success",
                });
              }
            },
            error: (response) => {
              this.$message({
                message: response.message,
                type: "error",
              });
            },
          });
        }
        else {
          let sceneBindGroup = {
            groupId: this.AddScene.taskgroupId,
            sceneId: sceneId,
            trigger: 0,
            sceneActionDetailList: data
          }
          ajax.post({
            url: this.$API.sceneBindGroup,
            data: sceneBindGroup,
            success: (response) => {
              if (response.success) {
                this.handleSceneTarget(sceneId);
                this.dialogTaskprodEditVisible = false
                this.addtargetProd = false
                this.$message({
                  message: '添加成功',
                  type: "success",
                });
              }
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
        }


      }
    },
    taskprodchange() {
      //console.log(callback)

      let matchingProducts = this.taskprodData.filter(
        product => product.id == this.AddScene.addtaskprodId
      );

      let data = matchingProducts.map(({ channelId, channelName, probeId, probeName, probeGuid, probeType }) => ({
        channelId,
        channelName,
        probeId,
        probeGuid,
        probeName,
        probeType,
        sceneId: this.AddScene.sceneId,
        groupId: this.AddScene.taskgroupId,
        open: 0,
        delay: 0,
        item: '',
        defertime: 0,
        airMode: 1,
        airSpeed: 1,
        airTemperatureset: 28,
        airWindDirection: 1,
        isair: airCategoryIds.includes(parseInt(probeType)),
        effectivetime: ['00:00', '23:59'],
        effectiveweek: [1, 2, 3, 4, 5, 6, 7],
      }));
      this.editTaskproddata = data[0]
      this.editTaskprodObj = true
    },

    //通过场景id获取场景联动记录
    getSceneLinkageRecord(id, title) {
      this.sceneLinkageRecordtitle = title

      ajax.get({
        url: this.$API.getSceneLinkageRecordBySceneId + id,
        success: (response) => {
          if (response.success) {
            if (response.data.length > 0) {
              let data = response.data.map(({ verifyCondition, actionDetailList, ...rest }) => {
                return {
                  ...rest,
                  verifyCondition: JSON.parse(verifyCondition),
                  actionDetailList: JSON.parse(actionDetailList),
                };
              });
              this.sceneLinkageRecorddata = data
            } else {
              this.sceneLinkageRecorddata = []

            }
            this.dialogSceneLinkageRecordVisible = true
          }
        },
        error: (response) => {
          this.$message({
            message: response.message,
            type: "error",
          });
        },
      });

    },
    browseVerify(data) {
      //console.log(data)
      this.browseVerifyData = data
      this.dialogBrowseVerifyVisible = true
    },
    browseAction(data) {

      this.browseActionData = data.map(({ item, ...rest }) => {
        const parsedItem = JSON.parse(item);
        return {
          ...rest,
          ...parsedItem,
          isair: airCategoryIds.includes(parseInt(rest.probeType))
        };
      });
      //console.log(this.browseActionData)
      this.dialogBrowseActionVisible = true
    },
    //空调温度设定
    handleTemperatureChange(changeType) {
      let temperatureNumber = parseInt(this.editTaskproddata.airTemperatureset);
      if (changeType == "add") {
        temperatureNumber = temperatureNumber + 1;
      } else {
        temperatureNumber = temperatureNumber - 1;
      }
      // 判断温度范围
      if (temperatureNumber > 31) {
        this.$message({
          message: "温度已经达到最高",
          type: "warning",
        });
        return;
      } else if (temperatureNumber < 16) {
        this.$message({
          message: "温度已经达到最低",
          type: "warning",
        });
        return;
      }
      this.editTaskproddata.airTemperatureset = temperatureNumber;
    },

  },
};